package org.example.backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.example.backend.constant.ResultCode;
import org.example.backend.dto.PageResult;
import org.example.backend.dto.Result;
import org.example.backend.entity.Leader;
import org.example.backend.entity.Order;
import org.example.backend.entity.OrderItem;
import org.example.backend.entity.Product;
import org.example.backend.exception.BusinessException;
import org.example.backend.mapper.LeaderMapper;
import org.example.backend.mapper.OrderItemMapper;
import org.example.backend.mapper.OrderMapper;
import org.example.backend.mapper.ProductMapper;
import org.example.backend.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 订单控制器
 * 提供订单查询、创建、处理等功能
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private LeaderMapper leaderMapper;

    @Autowired
    private ProductMapper productMapper;

    /**
     * 分页查询订单列表
     * @param current 当前页码
     * @param size 每页大小
     * @param orderNo 订单编号（可选，模糊查询）
     * @param leaderId 团长ID（可选，精确查询）
     * @param status 状态（可选，精确查询）
     * @param startTime 开始时间（可选）
     * @param endTime 结束时间（可选）
     * @return 分页结果
     */
    @GetMapping("/page")
    public ResponseEntity<Result<PageResult<Order>>> page(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) Long leaderId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String startTime,
            @RequestParam(required = false) String endTime) {

        Page<Order> page = new Page<>(current, size);

        LambdaQueryWrapper<Order> queryWrapper = Wrappers.<Order>lambdaQuery()
                .like(StringUtils.isNotBlank(orderNo), Order::getOrderNo, orderNo)
                .eq(leaderId != null, Order::getLeaderId, leaderId)
                .eq(status != null, Order::getStatus, status)
                .orderByDesc(Order::getCreateTime);

        // 添加时间范围查询
        if (StringUtils.isNotBlank(startTime)) {
            LocalDateTime start = LocalDateTime.parse(startTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            queryWrapper.ge(Order::getCreateTime, start);
        }
        if (StringUtils.isNotBlank(endTime)) {
            LocalDateTime end = LocalDateTime.parse(endTime, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            queryWrapper.le(Order::getCreateTime, end);
        }

        Page<Order> orderPage = orderMapper.selectPage(page, queryWrapper);

        // 查询团长信息
        orderPage.getRecords().forEach(order -> {
            Leader leader = leaderMapper.selectById(order.getLeaderId());
            if (leader != null) {
                // 可以添加额外信息，例如团长名称
                // 这里使用Map来存储额外信息
                Map<String, Object> extraInfo = new HashMap<>();
                extraInfo.put("leaderName", leader.getName());
                extraInfo.put("leaderPhone", leader.getPhone());
                // 可以将额外信息添加到订单对象中，但需要在Order实体类中添加相应的字段
            }
        });

        return ResponseUtil.success(new PageResult<>(orderPage.getTotal(), orderPage.getRecords()));
    }

    /**
     * 获取订单详情
     * @param id 订单ID
     * @return 订单详情
     */
    @GetMapping("/{id}")
    public ResponseEntity<Result<Map<String, Object>>> getById(@PathVariable Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseUtil.notFound("订单不存在");
        }

        // 查询订单明细
        List<OrderItem> orderItems = orderItemMapper.selectList(
                Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, id)
        );

        // 查询团长信息
        Leader leader = leaderMapper.selectById(order.getLeaderId());

        Map<String, Object> result = new HashMap<>();
        result.put("order", order);
        result.put("items", orderItems);
        if (leader != null) {
            result.put("leaderName", leader.getName());
            result.put("leaderPhone", leader.getPhone());
            result.put("leaderAddress", leader.getAddress());
        }

        return ResponseUtil.success(result);
    }

    /**
     * 创建订单
     * @param orderMap 订单信息
     * @return 操作结果
     */
    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Map<String, Object>>> save(@Valid @RequestBody Map<String, Object> orderMap) {
        // 获取订单基本信息
        Long leaderId = Long.valueOf(orderMap.get("leaderId").toString());
        List<Map<String, Object>> items = (List<Map<String, Object>>) orderMap.get("items");

        // 检查团长是否存在
        Leader leader = leaderMapper.selectById(leaderId);
        if (leader == null) {
            return ResponseUtil.badRequest("团长不存在");
        }

        // 检查商品是否存在，并计算总金额
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (Map<String, Object> item : items) {
            Long productId = Long.valueOf(item.get("productId").toString());
            Integer quantity = Integer.valueOf(item.get("quantity").toString());

            Product product = productMapper.selectById(productId);
            if (product == null) {
                return ResponseUtil.badRequest("商品不存在：ID=" + productId);
            }

            if (product.getStatus() == 0) {
                return ResponseUtil.badRequest("商品已下架：" + product.getName());
            }

            if (product.getStock() < quantity) {
                return ResponseUtil.badRequest("商品库存不足：" + product.getName());
            }

            // 计算小计金额
            BigDecimal subtotal = product.getPrice().multiply(new BigDecimal(quantity));
            totalAmount = totalAmount.add(subtotal);
        }

        // 生成订单编号
        String orderNo = generateOrderNo();

        // 创建订单
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setLeaderId(leaderId);
        order.setTotalAmount(totalAmount);
        order.setStatus(0); // 待处理
        orderMapper.insert(order);

        // 创建订单明细并更新库存
        for (Map<String, Object> item : items) {
            Long productId = Long.valueOf(item.get("productId").toString());
            Integer quantity = Integer.valueOf(item.get("quantity").toString());

            Product product = productMapper.selectById(productId);

            // 创建订单明细
            OrderItem orderItem = new OrderItem();
            orderItem.setOrderId(order.getId());
            orderItem.setProductId(productId);
            orderItem.setProductName(product.getName());
            orderItem.setProductPrice(product.getPrice());
            orderItem.setQuantity(quantity);
            orderItem.setSubtotal(product.getPrice().multiply(new BigDecimal(quantity)));
            orderItemMapper.insert(orderItem);

            // 更新库存
            Product updateProduct = new Product();
            updateProduct.setId(productId);
            updateProduct.setStock(product.getStock() - quantity);
            productMapper.updateById(updateProduct);
        }

        // 返回订单信息
        Map<String, Object> result = new HashMap<>();
        result.put("orderId", order.getId());
        result.put("orderNo", order.getOrderNo());
        result.put("totalAmount", order.getTotalAmount());

        return ResponseUtil.created(result);
    }

    /**
     * 更新订单状态
     * @param id 订单ID
     * @param status 状态值（0-待处理，1-已处理，2-配送中，3-已完成，4-已取消）
     * @return 操作结果
     */
    @PutMapping("/status")
    public ResponseEntity<Result<Void>> updateStatus(@RequestParam Long id, @RequestParam Integer status) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseUtil.notFound("订单不存在");
        }

        // 检查状态值是否有效
        if (status < 0 || status > 4) {
            return ResponseUtil.badRequest("无效的状态值");
        }

        // 如果订单已取消或已完成，不允许修改状态
        if (order.getStatus() == 3 || order.getStatus() == 4) {
            return ResponseUtil.badRequest("订单已" + (order.getStatus() == 3 ? "完成" : "取消") + "，无法修改状态");
        }

        // 如果要取消订单，需要恢复库存
        if (status == 4 && order.getStatus() != 4) {
            // 查询订单明细
            List<OrderItem> orderItems = orderItemMapper.selectList(
                    Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, id)
            );

            // 恢复库存
            for (OrderItem item : orderItems) {
                Product product = productMapper.selectById(item.getProductId());
                if (product != null) {
                    Product updateProduct = new Product();
                    updateProduct.setId(item.getProductId());
                    updateProduct.setStock(product.getStock() + item.getQuantity());
                    productMapper.updateById(updateProduct);
                }
            }
        }

        // 更新订单状态
        Order updateOrder = new Order();
        updateOrder.setId(id);
        updateOrder.setStatus(status);
        orderMapper.updateById(updateOrder);

        return ResponseUtil.success();
    }

    /**
     * 获取团长订单列表
     * @param leaderId 团长ID
     * @param status 状态（可选，精确查询）
     * @param orderNo 订单编号（可选，模糊查询）
     * @param startDate 开始日期（可选）
     * @param endDate 结束日期（可选）
     * @param page 页码（从0开始）
     * @param size 每页大小
     * @return 订单列表
     */
    @GetMapping("/leader")
    public ResponseEntity<Result<Page<Order>>> getLeaderOrders(
            @RequestParam Long leaderId,
            @RequestParam(required = false) Integer status,
            @RequestParam(required = false) String orderNo,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate,
            @RequestParam(required = false, defaultValue = "0") Integer page,
            @RequestParam(required = false, defaultValue = "10") Integer size) {

        Page<Order> pageParam = new Page<>(page, size);
        
        LambdaQueryWrapper<Order> queryWrapper = Wrappers.<Order>lambdaQuery()
                .eq(Order::getLeaderId, leaderId)
                .eq(status != null, Order::getStatus, status)
                .like(StringUtils.isNotBlank(orderNo), Order::getOrderNo, orderNo)
                .orderByDesc(Order::getCreateTime);

        // 添加日期范围查询
        if (StringUtils.isNotBlank(startDate)) {
            LocalDateTime start = LocalDateTime.parse(startDate + " 00:00:00", 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            queryWrapper.ge(Order::getCreateTime, start);
        }
        if (StringUtils.isNotBlank(endDate)) {
            LocalDateTime end = LocalDateTime.parse(endDate + " 23:59:59", 
                    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            queryWrapper.le(Order::getCreateTime, end);
        }

        Page<Order> orderPage = orderMapper.selectPage(pageParam, queryWrapper);

        return ResponseUtil.success(orderPage);
    }

    /**
     * 生成订单编号
     * @return 订单编号
     */
    private String generateOrderNo() {
        // 生成订单编号：年月日时分秒 + 4位随机数
        LocalDateTime now = LocalDateTime.now();
        String dateStr = now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));

        // 生成4位随机数
        Random random = new Random();
        int randomNum = random.nextInt(10000);
        String randomStr = String.format("%04d", randomNum);

        return dateStr + randomStr;
    }

    /**
     * 取消订单（GET方法）
     * @param id 订单ID
     * @return 操作结果
     */
    @GetMapping("/cancel")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> cancelOrderGet(@RequestParam Long id) {
        Order order = orderMapper.selectById(id);
        if (order == null) {
            return ResponseUtil.notFound("订单不存在");
        }

        // 如果订单已取消或已完成，不允许取消
        if (order.getStatus() == 3 || order.getStatus() == 4) {
            return ResponseUtil.badRequest("订单已" + (order.getStatus() == 3 ? "完成" : "取消") + "，无法再次取消");
        }

        // 查询订单明细
        List<OrderItem> orderItems = orderItemMapper.selectList(
                Wrappers.<OrderItem>lambdaQuery().eq(OrderItem::getOrderId, id)
        );

        // 恢复库存
        for (OrderItem item : orderItems) {
            Product product = productMapper.selectById(item.getProductId());
            if (product != null) {
                Product updateProduct = new Product();
                updateProduct.setId(item.getProductId());
                updateProduct.setStock(product.getStock() + item.getQuantity());
                productMapper.updateById(updateProduct);
            }
        }

        // 更新订单状态为已取消
        Order updateOrder = new Order();
        updateOrder.setId(id);
        updateOrder.setStatus(4); // 已取消
        orderMapper.updateById(updateOrder);

        return ResponseUtil.success();
    }

    /**
     * 取消订单（PUT方法）
     * @param id 订单ID
     * @return 操作结果
     */
    @PutMapping("/cancel")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Result<Void>> cancelOrder(@RequestParam Long id) {
        return cancelOrderGet(id);
    }

    /**
     * 导出订单为Excel文件
     * @param response HTTP响应对象
     * @throws IOException 如果导出过程中发生I/O错误
     */
    @GetMapping("/export")
    public void exportOrders(HttpServletResponse response) {
        try {
            // 查询所有订单
            List<Order> orders = orderMapper.selectList(Wrappers.<Order>lambdaQuery());

            // 创建工作簿和工作表
            try (XSSFWorkbook workbook = new XSSFWorkbook()) {
                Sheet sheet = workbook.createSheet("订单列表");

                // 创建表头
                Row headerRow = sheet.createRow(0);
                headerRow.createCell(0).setCellValue("订单编号");
                headerRow.createCell(1).setCellValue("团长ID");
                headerRow.createCell(2).setCellValue("总金额");
                headerRow.createCell(3).setCellValue("状态");
                headerRow.createCell(4).setCellValue("创建时间");

                // 填充数据
                int rowIndex = 1;
                for (Order order : orders) {
                    Row row = sheet.createRow(rowIndex);
                    row.createCell(0).setCellValue(order.getOrderNo());
                    row.createCell(1).setCellValue(order.getLeaderId());
                    row.createCell(2).setCellValue(order.getTotalAmount().toString());
                    
                    // 状态转换为文字
                    String statusText;
                    switch (order.getStatus()) {
                        case 0: statusText = "待处理"; break;
                        case 1: statusText = "已处理"; break;
                        case 2: statusText = "配送中"; break;
                        case 3: statusText = "已完成"; break;
                        case 4: statusText = "已取消"; break;
                        default: statusText = "未知"; break;
                    }
                    row.createCell(3).setCellValue(statusText);
                    
                    row.createCell(4).setCellValue(order.getCreateTime().toString());
                    rowIndex++;
                }

                // 自动调整列宽
                for (int i = 0; i < 5; i++) {
                    sheet.autoSizeColumn(i);
                }

                // 设置响应头
                response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("订单列表.xlsx", "UTF-8"));

                // 将工作簿写入响应流
                workbook.write(response.getOutputStream());
                response.getOutputStream().flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
            try {
                response.setContentType("application/json");
                response.setCharacterEncoding("utf-8");
                response.getWriter().println("{\"code\":500,\"message\":\"导出失败: " + e.getMessage() + "\"}");
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }
}
